package leetcode;

import java.util.*;

public class LeetCode90 {

    public static void main(String[] args) {
        LeetCode90 leetCode90 = new LeetCode90();
        leetCode90.subsetsWithDup(new int[]{1, 2, 2});
    }


    List<List<Integer>> result = new ArrayList<>();

    int[] nums;

    public List<List<Integer>> subsetsWithDup1(int[] nums) {
        this.nums = nums;
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            if (set.contains(nums[i]))
                continue;
            set.add(nums[i]);
            List<Integer> list = new ArrayList<>();
            list.add(nums[i]);
            helper(i + 1, list);
        }
        result.add(new ArrayList<>());
        return result;
    }

    private void helper(int index, List<Integer> list) {
        if (index == nums.length) {
            result.add(list);
            return;
        }
        List<Integer> tmpList = new ArrayList<>(list);
        tmpList.add((nums[index]));
        helper(index + 1, tmpList);
        helper(index + 1, new ArrayList<>(list));
    }
//------------------------------------------------------------------

    //选或者不选  用回溯法
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        Arrays.sort(nums); //排序
        getAns(nums, 0, new ArrayList<>(), ans);
        return ans;
    }

    private void getAns(int[] nums, int start, ArrayList<Integer> temp, List<List<Integer>> ans) {
        ans.add(new ArrayList<>(temp));
        for (int i = start; i < nums.length; i++) {
            //和上个数字相等就跳过
            if (i > start && nums[i] == nums[i - 1]) {
                continue;
            }
            temp.add(nums[i]);
            getAns(nums, i + 1, temp, ans);
            temp.remove(temp.size() - 1);
        }
    }

}
